﻿using System.Security.Cryptography;
using System.Text;

namespace Devonline.CloudService.Xfyun.FaceRecognition.FaceCompare;

/// <summary>
/// 人脸比对接口鉴权对象模型
/// </summary>
/// <param name="endpoint"></param>
public class AuthorizationModel(IFaceCompareEndpoint endpoint)
{
    private readonly IFaceCompareEndpoint _endpoint = endpoint;

    /// <summary>
    /// 获取签名
    /// </summary>
    /// <returns></returns>
    private string GetSignature()
    {
        ArgumentNullException.ThrowIfNull(_endpoint.Secret);
        using var sha256 = new HMACSHA256(Encoding.UTF8.GetBytes(_endpoint.Secret));
        var signature = $"host: {_endpoint.AuthorizationHost}\ndate: {_endpoint.AuthorizationDate}\n{_endpoint.RequestLine}";
        var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(signature));
        return Convert.ToBase64String(bytes);
    }
    /// <summary>
    /// 接口认证字符串
    /// </summary>
    private string Authorization => $"api_key=\"{_endpoint.AppId}\",algorithm=\"hmac-sha256\",headers=\"host date request-line\",signature=\"{GetSignature()}\"";

    /// <summary>
    /// 重载的 ToString 方法, 返回对象内容的整体表达式
    /// </summary>
    /// <returns></returns>
    public override string ToString() => $"?authorization={Convert.ToBase64String(Encoding.UTF8.GetBytes(Authorization))}&date={_endpoint.AuthorizationDate}&host={_endpoint.AuthorizationHost}";
}